<script setup lang="ts">
import { ElLoading } from 'element-plus'

import Editor from '@tinymce/tinymce-vue';
import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/silver';
import "tinymce/icons/default";
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/link';
import 'tinymce/plugins/image';
import 'tinymce/plugins/charmap';
import 'tinymce/plugins/hr';
import 'tinymce/plugins/anchor';
import 'tinymce/plugins/pagebreak';
import 'tinymce/plugins/imagetools';
import 'tinymce/plugins/searchreplace';
import 'tinymce/plugins/visualblocks';
import 'tinymce/plugins/visualchars';
import 'tinymce/plugins/code';
import 'tinymce/plugins/fullpage';
import 'tinymce/plugins/insertdatetime';
import './media/index';
// import 'tinymce/plugins/media';
import 'tinymce/plugins/nonbreaking';
import 'tinymce/plugins/save';
import 'tinymce/plugins/table';
import 'tinymce/plugins/contextmenu';
import 'tinymce/plugins/directionality';
// import 'tinymce/plugins/emoticons';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/textcolor';
import 'tinymce/plugins/colorpicker';
import 'tinymce/plugins/textpattern';
import 'tinymce/plugins/codesample';
import 'tinymce/plugins/preview';
import 'tinymce/plugins/print';
import 'tinymce/plugins/fullscreen';
import '@npkg/tinymce-plugins/importword';
import 'tinymce/plugins/wordcount';
import './tpLayout';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  fileAccept: {
    type: String,
    default: '.mp3, .mp4',
  },
  accept: {
    default: 'image/jpeg, image/png',
    type: String,
  },
  maxSize: {
    default: 9999999999999,
    type: Number,
  },
  uuid: {
    type: String,
    default: 'tinymce'
  },
  newSetting: {
    type: Object,
    default: () => ({})
  },
  toolbar: {
    type: Array,
    default: () => ([
      'newnote | undo redo | insert | styleselect | fontselect | formatselect | fontsizeselect | forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link media image hr | codesample | table print preview | fullscreen importword wordcount tpLayout'
    ])
  },
});

const emit = defineEmits(['update:modelValue'])

const value = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})


const state = ref({
  defaultSetting: {
    icons_url: '/tinymce/icons.js', // load icon pack
    icons: 'ax-color',
    branding: false,
    elementpath: false,
    height: 600,
    language_url: '/tinymce/zh_CN.js',
    language: 'zh_CN',
    skin_url: `/tinymce/skins/ui/oxide`,
    content_css: `/tinymce/skins/content/default/content.css`,
    // menubar: 'edit insert view format table tools',
    plugins: [
      'advlist lists link image charmap hr anchor pagebreak imagetools',
      'searchreplace visualblocks visualchars code fullpage fullscreen',
      'insertdatetime nonbreaking save table  directionality hr wordcount',
      'paste textpattern codesample preview media print importword tpLayout',
      // textcolor colorpicker contextmenu emoticons
    ],
    toolbar: props.toolbar,
    // 富文本一键排版自定义样式
    tp_layout_options: {
      style: {
        'text-align': 'justify',
        'text-indent': '2em',
        'line-height': 1.5
      },
      // filterTags: ['table>*', 'tbody'], //'table，'tbody','td','tr' 将会忽略掉 同时 table>*，忽略table 标签 以及所有子标签
      // clearStyle: ['text-indent'],//text-indent 将会被清除掉
      tagsStyle: {
        // 'table': {
        //   'line-height': 3,
        //   'text-align': 'center'
        // },
        // 'table,tbody,tr,td': { //支持并集选择
        //   'line-height': 2
        // },
        // 'tr>td,table>tbody': { //支持, 精准定位 通过 ' > '
        //   'line-height': 3,
        //   'text-align': 'center'
        // },
        // 图片居中
        'img': {
          'text-align': 'center'
        }
      }
    },
    autosave_interval: '20s',
    forced_root_block: 'p',
    force_p_newlines: true,
    importcss_append: true,
    content_style: `
          *                         { padding:0; margin:0; }
          html, body                { height:100%;padding:0; margin:0; }
          img                       { max-width:100%; height:auto; }
          a                         { text-decoration: none; }
          iframe                    { width: 100%; }
          table                     { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
          .mce-object-iframe        { width:100%; box-sizing:border-box; margin:0; padding:0; }
          ul,ol                     { list-style-position:inside; }
          video                     { max-width:100%; height:auto; }
        `,
    insert_button_items: 'image media link | inserttable',
    // CONFIG: Paste
    paste_retain_style_properties: 'all',
    paste_word_valid_elements: '*[*]', // word需要它
    paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
    paste_convert_word_fake_lists: false, // 插入word文档需要该属性
    paste_webkit_styles: 'all',
    paste_merge_formats: true,
    nonbreaking_force_tab: false,
    paste_auto_cleanup_on_paste: false,
    fontsize_formats: "12px 13px 14px 15px 16px 17px 18px 19px 20px 21px 22px 23px 24px 25px 26px 27px 28px 29px 30px 31px 32px 33px 34px 35px 36px 37px 38px 39px 40px",

    // CONFIG: StyleSelect
    style_formats: [
      {
        title: '首行缩进',
        block: 'p',
        styles: { 'text-indent': '2em' },
      },
      {
        title: '行高',
        items: [
          { title: '1', styles: { 'line-height': '1' }, inline: 'span' },
          {
            title: '1.5',
            styles: { 'line-height': '1.5' },
            inline: 'span',
          },
          { title: '2', styles: { 'line-height': '2' }, inline: 'span' },
          {
            title: '2.5',
            styles: { 'line-height': '2.5' },
            inline: 'span',
          },
          { title: '3', styles: { 'line-height': '3' }, inline: 'span' },
        ],
      },
    ],

    // FontSelect
    font_formats: `
        微软雅黑=微软雅黑;
        宋体=宋体;
        黑体=黑体;
        仿宋=仿宋;
        楷体=楷体;
        隶书=隶书;
        幼圆=幼圆;
        Andale Mono=andale mono,times;
        Arial=arial, helvetica,
        sans-serif;
        Arial Black=arial black, avant garde;
        Book Antiqua=book antiqua,palatino;
        Comic Sans MS=comic sans ms,sans-serif;
        Courier New=courier new,courier;
        Georgia=georgia,palatino;
        Helvetica=helvetica;
        Impact=impact,chicago;
        Symbol=symbol;
        Tahoma=tahoma,arial,helvetica,sans-serif;
        Terminal=terminal,monaco;
        Times New Roman=times new roman,times;
        Trebuchet MS=trebuchet ms,geneva;
        Verdana=verdana,geneva;
        Webdings=webdings;
        Wingdings=wingdings,zapf dingbats`,

    // Tab
    tabfocus_elements: ':prev,:next',
    object_resizing: true,

    // Image
    imagetools_toolbar:
      'rotateleft rotateright | flipv fliph | editimage imageoptions',
    convert_urls: false, // 避免同域名下图片地址杯改为相对路径
    images_upload_handler(blobInfo: any, success: any, failure: any) {
      if (blobInfo.blob().size > props.maxSize) {
        failure('文件体积过大');
      }
      async function uploadPic() {
        const formData = new FormData();
        // 服务端接收文件的参数名，文件数据，文件名
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        // const loading = ElLoading.service()
        // const res = await that.$api.upload(formData).catch(err => {
        //   loading.close()
        //   failure('上传失败');
        // });
        // loading.close()
        // if (res.code == 200) {
        //   let imgs = that.$utils.initFile(res.data.path_name)
        //   success(imgs);
        // } else {
        //   failure('上传失败');
        // }
      }
      if (props.accept.indexOf(blobInfo.blob().type) >= 0) {
        uploadPic();
      } else {
        failure('图片格式错误');
      }
    },
    media_live_embeds: true,
    file_picker_callback(callback: any, value: any, meta: any) {
      let mySaveBtn: any = null
      if (document.getElementsByClassName('tox-button').length > 0) {
        for (var i = 0; i < document.getElementsByClassName('tox-button').length; i++) {
          if (document.getElementsByClassName('tox-button')[i].innerHTML == '保存') {
            mySaveBtn = document.getElementsByClassName('tox-button')[i]
            mySaveBtn.disabled = true
          }
        }
      }
      let input = document.createElement('input');
      input.setAttribute('type', 'file');
      if (meta.filetype === 'media') {
        input.setAttribute('accept', props.fileAccept);
      } else if (meta.filetype === 'image') {
        input.setAttribute('accept', props.accept);
      } else if (meta.filetype === 'file') {

      }
      input.click();
      input.onchange = async function () {
        // let file = this.files[0];
        // const formData = new FormData();
        // formData.append('file', file, file.name);
        // const loading = that.$loading()
        // const res = await that.$api.upload(formData).catch(err => {
        //   loading.close()
        //   that.$message.error('上传失败');
        //   return
        // });
        // loading.close()
        // mySaveBtn.disabled = false
        // if (res.code == 200) {
        //   callback(that.$utils.initFile(res.data.path_name), { title: file.name, text: file.name });
        // } else {
        //   that.$message.error('上传失败');
        // }
      }
    },
    media_url_resolver(data: any, resolve: any) {
      if (!data.url) {
        resolve({ html: '' })
        return false
      }
      const urls = data.url.split('.')
      const url = JSON.stringify(data.url)
      if (urls[urls.length - 1] == 'mp4') {
        let html = `<p>
                <video class="mce-object mce-object-video" width="auto" height="auto" src=${url} controls="controls" controlslist="nodownload" preload="auto" poster="">
                </video>
                </p>
                `;



        resolve({ html })
      } else {
        let html = `<p>
                <audio src=${url} controls="controls" width="auto" height="auto" preload="auto">
                </audio>
                </p>
                `;
        resolve({ html })
      }

    },
  },
})
onMounted(() => {
  tinymce.init({});
})
onBeforeUnmount(() => {
  tinymce.remove();
})

// 初始化编辑器
function editorInit() {

}
// 保存文案到本地
function editorKeyDown() {

}
</script>

<template>
  <div class="richText">
    <!-- 富文本编辑器 -->
    <Editor v-model="value" :id="props.uuid" :init="state.defaultSetting" @onInit="editorInit" @onKeyDown="editorKeyDown">
    </Editor>
  </div>
</template>


<style lang="scss" scoped>
:deep(.tox-tinymce-aux) {
  z-index: 9999 !important;
}
</style>